package com.colorful.insuranceproject.utils;

import com.lovely3x.common.beans.LatLng;
import com.lovely3x.common.beans.LocationWrapper;
import com.lovely3x.jsonparser.Config;
import com.lovely3x.jsonparser.model.JSONObject;
import com.lovely3x.jsonparser.source.JSONSourceImpl;

import java.io.IOException;
import java.util.Locale;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * 支持的坐标为WGS84坐标系
 * 如果你使用其他的坐标系请先转换{@link LatLngTransformUtils}
 * 百度地图的geo转换器
 * 可以正向地理编码
 * 可以反向地理编码
 * Created by lovely3x on 16-2-1.
 */
public class BaiDuGeoCoder {

    public static final String BAI_DU_COMMON_AK = "c3GtGjUapZzmnrO2ZQYOxTN3";

    /**
     * 正向地理编码
     *
     * @param address 需要编码的地址
     * @return 编码的经纬度
     */
    public static LatLng geo(String address) {
        throw new UnsupportedOperationException();
    }

    /**
     * 反向地理编码
     *
     * @param latLng 需要反向地理编码的经纬度
     * @return 反向出来的经纬度
     */
    public static void reGeo(LatLng latLng, final CallBack callBack) {
        final double lat = latLng.lat;
        final double lng = latLng.lng;
        final String ak = BAI_DU_COMMON_AK;
        OkHttpClient client = new OkHttpClient();
        client.newCall(new Request.Builder().url(
                String.format(
                        Locale.US,
                        "http://api.map.baidu.com/geocoder/v2/?ak=%s&callback=renderReverse&location=%f,%f&output=json&pois=0&coordtype=wgs84ll",
                        ak, lat, lng)).get().build()).enqueue(new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {
                if (callBack != null) callBack.onResult(null, e);
            }


            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (callBack == null) {
                    return;
                }
                if (response.isSuccessful()) {
                    ResponseBody body = response.body();
                    String json = body.string();
                    json = json.substring(json.indexOf('{'), json.lastIndexOf(')'));
                    JSONSourceImpl source = new JSONSourceImpl(json);
                    JSONObject jo = new JSONObject(source, Config.createDefault());
                    if (jo.getInt("status") == 0) {
                        jo = jo.getJSONObject("result");
                        LocationWrapper lw = new LocationWrapper();
                        lw.setLatitude(lat);
                        lw.setLongitude(lng);
                        lw.setQualifiedName(jo.getString("formatted_address"));
                        jo = jo.getJSONObject("addressComponent");
                        lw.setProvince(jo.getString("province"));
                        lw.setCity(jo.getString("city"));
                        lw.setDistrict(jo.getString("district"));
                        callBack.onResult(lw, null);
                    } else {
                        callBack.onResult(null, new Exception("无法获取地址"));
                    }
                } else {
                    callBack.onResult(null, new Exception("HTTP 响应错误"));
                }
            }
        });
    }

    public interface CallBack {

        void onResult(LocationWrapper locationWrapper, Exception e);
    }
}
